package com.jl.encrypt.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * rsa非对称加密工具类
 */
public class JLRSA {

    /**
     * 获取密钥对
     *
     * @return
     */
    public static Map<String, String> getKey() {
        Map<String, String> map = new HashMap<>(2);
        KeyPair pair = SecureUtil.generateKeyPair("RSA");
        PrivateKey aPrivate = pair.getPrivate();
        PublicKey aPublic = pair.getPublic();
        map.put("privateKey", Base64.encode(aPrivate.getEncoded()));
        map.put("publicKey", Base64.encode(aPublic.getEncoded()));
        return map;
    }

    /**
     * 公钥加密
     *
     * @param str
     * @param publicKey
     * @return
     */
    public static String publicEncode(String str, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    /**
     * 私钥加密
     *
     * @param str
     * @param privateKey
     * @return
     */
    public static String privateEncode(String str, String privateKey) {
        RSA rsa = new RSA(privateKey, null);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);
        return Base64.encode(encrypt);
    }

    /**
     * 公钥解密
     *
     * @param str
     * @param publicKey
     * @return
     */
    public static String publicDecode(String str, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        byte[] decrypt = rsa.decrypt(Base64.decode(str), KeyType.PublicKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 私钥解密
     *
     * @param str
     * @param privateKey
     * @return
     */
    public static String privateDecode(String str, String privateKey) {
        RSA rsa = new RSA(privateKey, null);
        byte[] decrypt = rsa.decrypt(Base64.decode(str), KeyType.PrivateKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

}
